<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <div>父组件</div>
    <div>
        <button @click="handle">销毁事件</button>
    </div>
    <test-tom></test-tom>
    <test-jerry></test-jerry>
</div>

<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
    /*
    兄弟组件之间数据传递
     */
    //提供事件中心
    var hub = new Vue();

    Vue.component("test-tom", {
        data: function () {
            return {
                num: 0
            }
        },
        template: `
            <div>
                <div>TOM：{{num}}</div>
                <div>
                    <button @click="handle">点击</button>
                </div>
            </div>
        `,
        methods: {
            handle: function () {
                //触发兄弟组件的事件
                hub.$emit("jerry-event", 2);
            }
        },
        mounted: function () {
            //监听事件
            hub.$on("tom-event", (val) => {
                this.num += val;
            })
        }
    })

    Vue.component("test-jerry", {
        data: function () {
            return {
                num: 0
            }
        },
        template: `
            <div>
                <div>JERRY：{{num}}</div>
                <div>
                    <button @click="handle">点击</button>
                </div>
            </div>
        `,
        methods: {
            handle: function () {
                //触发兄弟组件的事件
                hub.$emit("tom-event", 1);
            }
        },
        mounted: function () {
            //监听事件
            hub.$on("jerry-event", (val) => {
                this.num += val;
            })
        }
    })

    var vue = new Vue({
        el: "#app",
        data: {},
        methods: {
            handle: function () {
                //销毁事件
                hub.$off("tom-event");
                hub.$off("jerry-event");
            }
        }
    })

</script>
</body>
</html>
